import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import locale from 'element-plus/es/locale/lang/zh-cn'
import { useLayoutStore } from './store/modules/layout'

const app = createApp(App)
app.use(createPinia())
app.use(ElementPlus, { locale })
app.use(router)

const iconsNameHash = {}

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
    iconsNameHash[key] = 1
}

app.mount('#app')

export const IconsNameHash = iconsNameHash

const loginRoutePath = '/login'
const defaultRoutePath = '/'
const whiteList = ['/login', '/register', '/wechatqrcode', '/verify']

router.beforeEach(async (to, from) => {

    const aToken = localStorage.getItem('access_token')
    // console.log(to, from)

    const layoutStore = useLayoutStore()

    // isNotNeedToken 不需要 token 的界面，白名单中路由
    const isNotNeedToken = whiteList.includes(to.path.toLowerCase())
    // isLoginPage 是否已经登陆，即有 token 了
    const isLogged = !!layoutStore.status.accessToken

    if (isNotNeedToken) {
        if (isLogged) {
            return defaultRoutePath
        }
        return true
    } else {
        if (!isLogged) {
            return loginRoutePath
        }
        if (layoutStore.menubar.menuList.length === 0) {
            await layoutStore.generateRoutes()
            return to.fullPath
        }
    }
    return true
})


export default router